package com.coldworks.coldjoke.task;

import java.io.IOException;

import android.content.Context;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONObject;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.util.CONST;
import com.coldworks.coldjoke.util.NetworkUtil;

public class LogoutTask extends BaseThread {

	private String url;
	private Context context;

	public LogoutTask(Context context) {
		this.context = context;
		this.url = CONST.URL.PROFILE + "?action=logout";
	}

	@Override
	public void run() {

		HttpPost httpPost = new HttpPost(url);
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			httpPost.setHeader("Cookie", "webpy_session_id=" + sessionId);
			HttpResponse response = BaseNetworkManager.getInstance()
					.createHttpClient(context).execute(httpPost);
			if (isInterrupted()) {
				log.info("cancelled");
				return;
			}
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}
				if (jsonObject == null) {
					log.info("run error");
					return;
				}
				log.info(jsonObject.toString());
			} else {
				log.warn(String.valueOf(response.getStatusLine()
						.getStatusCode()));
			}
		} catch (ClientProtocolException e) {
			log.error("", e);
			return;
		} catch (IOException e) {
			log.error("", e);
			return;
		}
	}

}
